﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace Tools.Base
{
    public class SystemInfo
    {
        private static PerformanceCounter cpuUsage = null;
        private static int nCpuCount = 0;
        public static bool GetCPUValue(out float fValue, out string strMsg)
        {
            fValue = 0f;
            strMsg = "OK";
            try
            {
                if (SystemInfo.cpuUsage == null)
                {
                    Process process = Process.GetCurrentProcess();
                    SystemInfo.cpuUsage = new PerformanceCounter("Process", "% Processor Time", process.ProcessName);
                    SystemInfo.nCpuCount = Environment.ProcessorCount;
                }
                if (SystemInfo.nCpuCount <= 0)
                {
                    fValue = 0f;
                    strMsg = "CPU count is zero.";
                    return false;
                }
                if (SystemInfo.cpuUsage == null)
                {
                    fValue = 0f;
                    strMsg = "cpuUsage is null.";
                    return false;
                }
                float usage = SystemInfo.cpuUsage.NextValue();
                fValue = usage / (float)SystemInfo.nCpuCount;
                return true;
            }
            catch (Exception ex)
            {
                fValue = 0f;
                strMsg = ex.ToString();
            }
            return false;
        }

        /// <summary>
        /// 获取当前进程内存占用（KB）
        /// </summary>
        /// <returns></returns>
        static public double GetProcessMemory()
        {
            double fValue = Process.GetCurrentProcess().WorkingSet64;
            return fValue / 1024;
        }
    }
}
